﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace ZR.Common
{
    /// <summary>
    /// 身份认证
    /// </summary>
    public static class IdentityAuthHelper
    {
        #region 百度2要素接口

        // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId = "IfPGTiQEhK8Umq8vcfmDsn45"; //API Key
        // 百度云中开通对应服务应用的 Secret Key
        private static String clientSecret = "BB7cEOhjXGrmjTaf9NPcDywama0mhoNE"; //Secret Key

        //获取Token
        public static String getAccessToken()
        {
            String authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new HttpClient();
            List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
            paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
            paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));

            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            String result = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(result);
            return result;
        }

        #endregion

        #region 百度3要素接口

        private const String host = "https://telthree.api.bdymkt.com";
        private const String path = "/lundear/telThree";
        private const String method = "GET";
        private const String appcode = "8d32fae853ad43858625418f3371b219 ";
        public static String IdentificationByBaidu(string Phone, string IdCard, string Name)
        {
            string usr = System.Web.HttpUtility.UrlEncode(Name, System.Text.Encoding.UTF8);
            String querys = "idcard=" + IdCard.Trim() + "&mobile=" + Phone.Trim() + "&name=" + usr;
            String bodys = "";
            String url = host + path;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("X-Bce-Signature", "AppCode/" + appcode);
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                string ret = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();
                return ret;
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
                string ret = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();
                return ret;
            }
        }

        #endregion

        #region 阿里云三要素接口

       // private const String host = "https://qrymobile.market.alicloudapi.com";
       // private const String path = "/lundear/telThree";
       // private const String method = "GET";
       // private const String appcode = "054a79a6bb4c41988148dcdfdceffbd6";

       ///// <summary>
       ///// 调取接口
       ///// </summary>
       ///// <param name="Phone">手机号码</param>
       ///// <param name="IdCard">身份证号</param>
       ///// <param name="Name">姓名</param>
       ///// <returns></returns>
       // public static String IdentificationByAliyun(string Phone,string IdCard,string Name) 
       // {
       //     string usr = System.Web.HttpUtility.UrlEncode(Name, System.Text.Encoding.UTF8);
       //     String querys = "idcard="+IdCard.Trim()+"&mobile="+Phone.Trim()+"&name="+ usr;
       //     String bodys = "";
       //     String url = host + path;
       //     HttpWebRequest httpRequest = null;
       //     HttpWebResponse httpResponse = null;

       //     if (0 < querys.Length)
       //     {
       //         url = url + "?" + querys;
       //     }

       //     if (host.Contains("https://"))
       //     {
       //         ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
       //         httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
       //     }
       //     else
       //     {
       //         httpRequest = (HttpWebRequest)WebRequest.Create(url);
       //     }
       //     httpRequest.Method = method;
       //     httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
       //     if (0 < bodys.Length)
       //     {
       //         byte[] data = Encoding.UTF8.GetBytes(bodys);
       //         using (Stream stream = httpRequest.GetRequestStream())
       //         {
       //             stream.Write(data, 0, data.Length);
       //         }
       //     }
       //     try
       //     {
       //         httpResponse = (HttpWebResponse)httpRequest.GetResponse();
       //         string ret = httpResponse.ContentEncoding;
       //         return httpResponse.Headers.ToString();
       //     }
       //     catch (WebException ex)
       //     {
       //         httpResponse = (HttpWebResponse)ex.Response;
       //         string err = httpResponse.Headers.ToString();
       //         return err;
       //     }
            
       //     //Console.WriteLine(httpResponse.StatusCode);
       //     //Console.WriteLine(httpResponse.Method);
       //     //Console.WriteLine(httpResponse.Headers);
       //     //Stream st = httpResponse.GetResponseStream();
       //     //StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
       //     //Console.WriteLine(reader.ReadToEnd());
       //     //Console.WriteLine("\n");
       // }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
        #endregion

    }
}
